package com.wolfeyes.framework.alipay.controller;

import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wolfeyes.framework.alipay.config.AlipayConfig;
import com.wolfeyes.framework.alipay.param.PayParam;
import com.wolfeyes.framework.alipay.service.AlipayService;
import com.wolfeyes.common.response.ResponseResult;
import com.wolfeyes.system.domain.vo.SysBillVo;
//import com.wolfeyes.web.controller.BaseController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @see Talk is cheap, Show me the code. -- Linus Torvalds
 * @title 第三方支付-支付宝模块接入-控制器
 * @author yanyljava
 * @email yanyljava@qq.com
 * @create 2022-08-17 10:36
 */
@Slf4j
@CrossOrigin
//@RestController
@Controller
@RequiredArgsConstructor
@RequestMapping("/alipay")
public class AlipayPayController /*extends BaseController*/ {
	
	//@Autowired
	//AlipayConfig alipayConfig;
	private final AlipayConfig alipayConfig;
	
	private final AlipayService alipayService;
	
	/**
	 * @param sysBillVo 接收前端增加订单的数据(请求体)
	 * @param request 请求
	 * @param response 响应
	 * @return ResponseResult Restful API接口响应的统一结果封装对象
	 * @throws IOException IO异常信息
	 * @throws AlipayApiException 第三支付宝封装的异常信息
	 */
	@ResponseBody
	@PostMapping("/payCreate")
	public ResponseResult payCreate(@RequestBody SysBillVo sysBillVo,
			HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
		
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(this.alipayConfig.getGatewayUrl(), this.alipayConfig.getAppId(),
				this.alipayConfig.getMerchantPrivateKey(), this.alipayConfig.getFormat(), this.alipayConfig.getCharset(),
				this.alipayConfig.getAlipayPublicKey(), this.alipayConfig.getSignType());

		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(this.alipayConfig.getReturnUrl());
		alipayRequest.setNotifyUrl(this.alipayConfig.getNotifyUrl());

		//商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = null;

		//订单编号，不可重复
		out_trade_no = sysBillVo.getSysBill().getBillId().toString();
		//out_trade_no = new String(request.getParameter("COrderCde").getBytes("ISO-8859-1"), "UTF-8");
		//out_trade_no="200000055556";
		//付款金额，必填
		long total_amount = sysBillVo.getSysBill().getSysSession().getSessionPrice().longValue()*JSON.parseArray(sysBillVo.getSysBill().getSeats()).size();
		//String total_amount = new String(request.getParameter("NPrm").getBytes("ISO-8859-1"), "UTF-8");
		//String total_amount="5000";
		System.out.println("out_trade_no="+out_trade_no+",total_amount="+total_amount);
		//订单名称，必填
		//String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
		String subject = "测试订单";
		//商品描述，可空
		//String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");
		String body= "";
		alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
				+ "\"total_amount\":\"" + total_amount + "\","
				+ "\"subject\":\"" + subject + "\","
				+ "\"body\":\"" + body + "\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

		//若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
		//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
		//		+ "\"total_amount\":\""+ total_amount +"\","
		//		+ "\"subject\":\""+ subject +"\","
		//		+ "\"body\":\""+ body +"\","
		//		+ "\"timeout_express\":\"10m\","
		//		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

		//请求结果
		String result = alipayClient.pageExecute(alipayRequest).getBody();

		return ResponseResult.success("调用成功", result);

	}

	/*@PostMapping(value = "/create")
	@ApiOperation("创建订单")
	public ResponseResult create(@ApiParam("订单号") @RequestParam("orderNo") String orderNo,
						 @ApiParam("订单名称") @RequestParam("orderName") String orderName,
						 @ApiParam("支付金额") @RequestParam("payPrice") String payPrice) {
		//发起支付
		String result = alipayService.create(orderNo, orderName, payPrice);
		return ResponseResult.success("调用成功", result);
	}*/
	@ResponseBody
	@PostMapping(value = "/payCreate22")
	@ApiOperation("创建订单")
	public ResponseResult create(@RequestBody PayParam payParam) {
		//发起支付
		String orderNo = payParam.orderNo;
		String orderName = payParam.orderName;
		String payPrice = payParam.payPrice;
		String serialNumber = payParam.serialNumber;
		//redisUtil.set(serialNumber,user,60*5);   //5分钟
		//redisUtil.set(orderNo,serialNumber,60*5);   //5分钟
		
		// 请求结果
		String result = this.alipayService.create(orderNo, orderName, payPrice);
		return ResponseResult.success("调用成功", result);
	}
	
	/**
	 * 支付宝同步通知，用户支付成功后浏览器跳转的页面，本地环境即可测试
	 * 本地测试时，在此更新订单状态和交易记录
	 * @return ResponseResult Restful API接口响应的统一结果封装对象
	 * @throws IOException 
	 */
	@GetMapping(value = "/paySuccess")
	//@RequestMapping("/paySuccess") // get请求
	public void payReturnUrl(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession httpSession,
			@CookieValue(name="mysession",defaultValue = "") String mysession) throws AlipayApiException, IOException {
		//获取支付宝GET请求回传过来的反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		//调用SDK验证签名
		boolean signVerified = AlipaySignature.rsaCheckV1(params, this.alipayConfig.getAlipayPublicKey(),
				this.alipayConfig.getCharset(), this.alipayConfig.getSignType());

		//——请在这里编写您的程序（以下代码仅作参考）——
		if(signVerified) {
			//商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//付款金额
			String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
			Map<String,String> map = new HashMap<>();
			map.put("orderNo",out_trade_no);
			map.put("payNo",trade_no);
			map.put("payWay","6");   //支付宝
			map.put("payNum",total_amount);   //支付宝
			//orderService.updateOrderPayStatus(JSON.toJSONString(map));
			//修改保单状态，未待承保
			//orderService.updatePlyPkgBaseStatus(out_trade_no,"0");//修保单带承保0状态
			// out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
			//支付处理成功后的回调地址(前端Vue项目路径)
			String callBackUrl = this.alipayConfig.getCallBackUrl() + "/" + out_trade_no + "?orderId=" + out_trade_no;
			
			response.sendRedirect(callBackUrl);
		} else {
			//out.println("验签失败");
		}
		
	}

	@GetMapping(value = "/paySuccess22")
	@ApiOperation("支付成功同步回调接口")
	public void paySuccess(@RequestParam Map<String, String> map, HttpServletResponse response) {
		try {
			String tradeNo = map.get("out_trade_no");
			System.out.println("订单号：" + tradeNo);
			String payAmount = map.get("total_amount");
			//String serialNumber =(String) redisUtil.get(tradeNo);
			//User user = (User) redisUtil.get(serialNumber);
			//response.sendRedirect(PropertiesUtil.getCallBack() + "/#/specialDetail?id="+courseId+"&serialNumber=ERROR");
			response.sendRedirect("/paySuccess");
		} catch (IOException e) {
			log.error("支付成功，但重定向失败 error={}", e.toString());
		}
	}
	
	/**
	 * 支付宝异步通知，真实环境使用，在此更新订单状态和交易记录
	 */
	@ResponseBody
	@PostMapping(value = "/payNotify")
	//@RequestMapping("/payNotify") // post请求
	public void payNotifyUrl(@RequestParam Map<String, String> map) {
		String tradeStatus = map.get("trade_status");
		if (tradeStatus.equals("TRADE_SUCCESS")) {
			String payTime = map.get("gmt_payment");
			String tradeNo = map.get("out_trade_no");
			String tradeName = map.get("subject");
			String payAmount = map.get("buyer_pay_amount");
			log.info("[支付成功] {交易时间：{},订单号：{},订单名称：{},交易金额：{}}", payTime, tradeNo, tradeName, payAmount);
		}
	}
	
	@ResponseBody
	@PostMapping(value = "/payNotify22")
	@ApiOperation("支付成功异步回调接口")
	public void payNotify(@RequestParam Map<String, String> map) {
		String tradeStatus = map.get("trade_status");
		if (tradeStatus.equals("TRADE_SUCCESS")) {
			String payTime = map.get("gmt_payment");
			String tradeNo = map.get("out_trade_no");
			String tradeName = map.get("subject");
			String payAmount = map.get("buyer_pay_amount");
			log.info("[支付成功] {交易时间：{},订单号：{},订单名称：{},交易金额：{}}", payTime, tradeNo, tradeName, payAmount);
		}
	}
	
	@ResponseBody
	@PostMapping(value = "/refund")
	@ApiOperation("订单退款")
	public ResponseResult refund(@ApiParam("订单号") @RequestParam("orderNo") String orderNo,
						 @ApiParam("退款金额") @RequestParam("payPrice") String payPrice) {
		//发起支付
		try {
			this.alipayService.refund(orderNo, payPrice);
		} catch (AlipayApiException e) {
			log.error("【支付宝支付】退款失败 error={}", e.toString());
			return ResponseResult.error("退款失败");
		}
		return ResponseResult.success("退款成功");
	}

}


